<?php
/**
 * Created by jinqiang on 2024/6/12 10:01.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Services\Banshi;


use App\Http\Models\Mysql\ExportOrderProductTable;
use App\Http\Models\Mysql\SsyMaterialImagesTable;
use App\Http\Models\Mysql\SsyNewProductProcessSheetTable;
use App\Http\Models\Mysql\SsyNewProductsLogTable;
use App\Http\Models\Mysql\SsyNewProductsSealedSampleTable;
use App\Http\Models\Mysql\SsyNewProductsSizeTable;
use App\Http\Models\Mysql\SsyProductlistBangdinNewTable;
use App\Http\Models\Mysql\SsyStyleAttachTable;
use App\Http\Models\Mysql\SsyStyleImagesTable;
use App\Http\Models\Mysql\StyleBomColourConfigTable;
use App\Http\Models\Mysql\StyleBomSizeConfigTable;
use App\Http\Models\Mysql\StyleBomTable;
use App\Http\Models\Mysql\StyleColourTable;
use App\Http\Models\Mysql\StylePrintingTable;
use App\Http\Models\Mysql\StyleSampleProcessesTable;
use App\Http\Models\Mysql\StyleSizeTable;
use App\Http\Models\Mysql\StyleT4Table;
use App\Http\Models\Mysql\StyleT50Table;
use App\Http\Models\Mysql\StyleT68Table;
use App\Http\Models\Mysql\StyleTable;
use App\Http\Models\Mysql\StyleTagTable;
use App\Http\Models\Mysql\T17Table;
use App\Http\Models\Mysql\VerifyPriceTable;
use App\Http\Repository\CommonRepository;
use App\Http\Repository\FeishuRepository;
use App\Http\Repository\LogRepository;
use Illuminate\Support\Facades\DB;

class DesignService
{
    public function search($param)
    {
        $conn = (new StyleTable());
        if(isset($param['state']) && $param['state'] != ""){
            $conn = $conn->where('state', (Int)$param['state']);
        }
        if($param['name'] ?? ""){
            $conn = $conn->where('name', 'like', "%".$param['name']."%");
        }
        if($param['number'] ?? ""){
            $numbers = explode(",", $param['number']);
            if(count($numbers) > 1){
                $conn = $conn->whereIn('number', $numbers);
            }else if(preg_match("/^[a-zA-Z]/is", $param['number'])){
                $conn = $conn->where('number', 'like', $param['number']."%");
            }else{
                $conn = $conn->where('number', 'like', "%".$param['number']."%");
            }
        }
        if($param['package_number'] ?? ""){
            $t17Obj = (new T17Table())->where('number', $param['package_number'])->first();
            if(empty($t17Obj)){
                return ['data' => [], 'total' => 0];
            }
            $conn = $conn->where('t17_id', $t17Obj->id);
        }
        if($param['year_month'] ?? ""){
            $yearMonth = explode("-", $param['year_month']);
            $conn = $conn->where('year', $yearMonth[0])->where('month', $yearMonth[1]);
        }
        if($param['designer'] ?? ""){
            $conn = $conn->where('designer', $param['designer']);
        }
        if($param['f3'] ?? ""){
            $conn = $conn->where('f3', $param['f3']);
        }
        if($param['product_category_id'] ?? ""){
            $conn = $conn->where('product_category_id', (Int)$param['product_category_id']);
        }
        if($param['category_id'] ?? ""){
            $conn = $conn->where('detail_category_id', (Int)$param['category_id']);
        }
        if($param['brand_id'] ?? ""){
            $conn = $conn->where('brand_id', (Int)$param['brand_id']);
        }
        if($param['season_id'] ?? ""){
            $conn = $conn->where('season_id', (Int)$param['season_id']);
        }
        if($param['paper_designer'] ?? ""){
            $conn = $conn->where('paper_designer', $param['paper_designer']);
        }
        if($param['embroider_designer'] ?? ""){
            $conn = $conn->where('embroider_designer', $param['embroider_designer']);
        }
        if($param['materiel'] ?? ""){
            $bomList = (new StyleBomTable())->where('is_product', 0)->where('materiel', 'like', '%'.$param['materiel']."%")->groupBy(['style_id'])->get(['style_id'])->toArray();
            $styleIds = array_column($bomList, 'style_id');
            $conn = $conn->whereIn('id', $styleIds);
        }
        if($param['supplier'] ?? ""){
            $bomList = (new StyleBomTable())->where('is_product', 0)->where('supplier', 'like', '%'.$param['supplier']."%")->groupBy(['style_id'])->get(['style_id'])->toArray();
            $styleIds = array_column($bomList, 'style_id');
            $conn = $conn->whereIn('id', $styleIds);
        }
        if($param['is_subject'] ?? ""){
            $subjects = array_column(config("scm.subject"), 'brand_id', 'is_subject');
            $conn = $conn->where('brand_id', $subjects[$param['is_subject']]);
        }
        $res = $conn->orderBy("creation_time", "desc")->orderBy("year", "desc")->orderBy("month", "desc")->orderBy("t17_id", 'desc')->orderBy('id', 'desc')
            ->paginate((Int)$param['limit'])->toArray();
        $numbers = array_column($res['data'], 'number');
        $t17Ids = array_column($res['data'], 't17_id');
        //缩略图
        $imgRes = (new SsyStyleImagesTable())->whereIn('type_no', $numbers)->get(["type_no", "thumb_images"])->toArray();
        $imgs = array_column($imgRes, 'thumb_images', 'type_no');
        //套装编码
        $packageRes = (new T17Table())->whereIn('id', $t17Ids)->get(['id', 'number'])->toArray();
        $packages = array_column($packageRes, 'number', 'id');
        //是否赠品
        $productRes = (new SsyNewProductProcessSheetTable())->whereIn("type_no", $numbers)->get(['type_no', 'is_gif'])->toArray();
        $products = array_column($productRes, 'is_gif', 'type_no');
        foreach ($res['data'] as &$item){
            $item['thumb_images'] = $imgs[$item['number']] ?? "";
            $item['creation_time'] = date("Y-m-d",$item['creation_time']+1512460800);
            $item['package_number'] = $packages[$item['t17_id']] ?? "";
            $item['is_gif'] = $products[$item['number']] ?? 0;
        }
        unset($item);
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function detail($number)
    {
        $res = (new StyleTable())->where('number', $number)->first()->toArray();
        $res['creation_time'] = date("Y-m-d",$res['creation_time']+1512460800);
        //上新月份
        $res['year_month'] = date('Y-m', strtotime($res['year']."-".$res['month']));
        //绣花总针数
        $res['embroidery_stitches_number'] = (new StyleT50Table())->where('style_id', $res['id'])->sum("f52");
        //套装编码
        $packageRes = (new T17Table())->where('id', $res['t17_id'])->first(['number']);
        $res['package_number'] = !empty($packageRes) ? $packageRes->number : "";
        //工艺类型
        $styleT68Res = (new StyleT68Table())->where('style_id', $res['id'])->first();
        $res['t68'] = $styleT68Res->t68 ?? "";
        $res['t68_id'] = $styleT68Res->t68_id ?? "";
        $res['style_t68_id'] = $styleT68Res->id ?? "";
        //纹样描述
        $res['style_tag'] = (new StyleTagTable())->where('style_id', $res['id'])->get()->toArray();
        //商品属性
        $res['style_t4'] = (new StyleT4Table())->where('style_id', $res['id'])->get(['id as _id', 't4 as name', 't4_id as id'])->toArray();
        //获取图片
        $imageRes = (new SsyStyleImagesTable())->where('type_no', $number)->first();
        $res['img'] = [];
        if(!empty($imageRes)){
            $res['img'] = [
                'images' => $imageRes->images,
                'images_list' => json_decode($imageRes->images_list, true),
                'thumb_images_list' => json_decode($imageRes->thumb_images_list, true),
            ];
        }
        //绣花bom
        $bomXh = (new StyleT50Table())->where('style_id', $res['id'])->orderBy('position', 'asc')->get()->toArray();
        foreach ($bomXh as &$item) {
            $item['f54'] = (Double)$item['f54'];
            $item['f55'] = (Double)$item['f55'];
        }
        unset($item);
        return [
            'style' => $res,
            'style_colour' => (new StyleColourTable())->where('style_id', $res['id'])->orderBy('position', 'asc')->get()->toArray(),
            'material_data' => $this->detailMaterial($res['id']),
            'size_list' => $this->detailSize($number, $res['id']),
            'bom_data' => $this->detailMaterial($res['id'], 1),
            'bom_xh_data' => $bomXh,
            'yy_gs_data' => (new StyleSampleProcessesTable())->where('style_id', $res['id'])->orderBy('position', 'asc')->get()->toArray(),
            'wash_data' => (new SsyProductlistBangdinNewTable())->where('type_no', $number)->get()->toArray(),
            'file_data' => (new SsyNewProductsSealedSampleTable())->where('type_no', $number)->orderBy("createtime", "desc")->get()->toArray()
        ];
    }

    //物料清单 is_product=0 ; 大货BOM is_product=1
    public function detailMaterial($styleId, $isProduct = 0)
    {
        $styleBomList = (new StyleBomTable())->where('style_id', $styleId)->where("is_product", $isProduct)->orderBy('position', 'asc')->get()->toArray();
        $styleBomIds = array_column($styleBomList, 'id');
        //款号颜色
        $styleColourList = (new StyleColourTable())->where('style_id', $styleId)->get(['id', 'style_id', 'colour'])->toArray();
        $styleBomColourConfigList = (new StyleBomColourConfigTable())->where('style_id', $styleId)->where("is_product", $isProduct)->get()->toArray();
        $styleBomColourConfigMap = [];
        foreach ($styleBomColourConfigList as $item){
            $colourContentList = json_decode($item['content'], true);
            $colourContent = isset($colourContentList[0]) ? [
                array_merge(['style_bom_colour_id' => $item['id'], 'code_ch' => CommonRepository::getColor($colourContentList[0]['code'])], $colourContentList[0])
            ] : [['style_bom_colour_id' => $item['id']]];
            foreach ($styleColourList as $colourItem){
                if(empty($item['style_colour_id']) || $colourItem['id'] == $item['style_colour_id']){
                    $styleBomColourConfigMap[$item['style_bom_id']][$colourItem['id']] = $colourContent;
                }
            }
        }
        $styleBomSizeConfigList = (new StyleBomSizeConfigTable())->where('style_id', $styleId)->whereIn('style_bom_id', $styleBomIds)->get()->toArray();
        $styleBomSizeConfigMap = array_column($styleBomSizeConfigList, null, 'style_bom_id');
        $materialIds = array_column($styleBomList, 'materiel_id');
        $materialImageList = (new SsyMaterialImagesTable())->whereIn('material_id', $materialIds)->get()->toArray();
        $materialImageMap = array_column($materialImageList, 'images', 'material_id');
        foreach($styleBomList as &$item){
            $item['price'] = (Double)$item['price'];
            $item['style_bom_colour_config'] = $styleBomColourConfigMap[$item['id']] ?? [];
            $item['style_bom_size_config'] = [];
            if(isset($styleBomSizeConfigMap[$item['id']])){
                $content = json_decode($styleBomSizeConfigMap[$item['id']]['content'], true);
                $srArr = empty($styleBomSizeConfigMap[$item['id']]['sr']) ? [] : explode(":", $styleBomSizeConfigMap[$item['id']]['sr']);
                $item['style_bom_size_config'] = [
                    'id' => $styleBomSizeConfigMap[$item['id']]['id'],
                    'amount' => (Double)($styleBomSizeConfigMap[$item['id']]['amount']),
                    'content' => empty($content) && $item['materiel_major_unit']=='条' ? [4 => ["name" => "长度(cm)", "value" => 0]] : $content,
                    'material_sr_e' => $srArr[0] ?? 0,
                    'material_sr_w' => $srArr[1] ?? 0,
                ];
            }
            $item['img'] = $materialImageMap[$item['materiel_id']] ?? "";
            $item['materiel_style_list'] = $materialStyleMap[$item['materiel_number']] ?? [];
        }
        unset($item);
        return $styleBomList;
    }

    //获取物料在用款号
    public function getMaterielStyle($materielNumber, $isProduct)
    {
        $materialBoms = (new StyleBomTable())->where('is_product', $isProduct)->where('materiel_number', $materielNumber)->groupBy(["materiel_number", "style_id"])
            ->get(['style_id', 'materiel_number'])->toArray();
        $styleIds = array_column($materialBoms, 'style_id');
        $list = (new StyleTable())->whereIn('id', $styleIds)->get(['id', 'number', 'name'])->toArray();
        return $list;
    }

    //尺码
    public function detailSize($typeNo, $styleId)
    {
        $res = (new SsyNewProductsSizeTable())->where('type_no', $typeNo)->first();
        $sizeList = [];
        if(!empty($res) && !empty($res->plank_house_table_title)){
            $plankHouseTableTitle = json_decode($res->plank_house_table_title, true);
            $codeList = $plankHouseTableTitle['code_list'] ?? [];
            foreach ($codeList as $item) {
                if($item['is']){
                    $sizeList[] = $item;
                }
            }
        }else{
            //数加的尺码
            $codeList = (new StyleSizeTable())->where('style_id', $styleId)->get()->toArray();
            foreach ($codeList as $item){
                $sizeList[] = [
                    "size_code" => ['id'=>1,"title"=>$item['size_number']],
                    "height_code" => ['id'=>1,"title"=>$item['size']],
                    "waist_code" => ['id'=>1,"title"=> '']
                ];
            }
        }
        return $sizeList;
    }

    //尺寸表信息
    public function detailRule($typeNo)
    {
        $res = (new SsyNewProductsSizeTable())->where('type_no', $typeNo)->first();
        if(empty($res)){
            return ['data' => ['mas' => '上新表未发现数据'], 'log' => []];
        }
        $res = $res->toArray();
        if(!empty($res['wear_image'])){
            $wearImage = json_decode($res['wear_image'], true);
            $res['wear_image'] = $wearImage ?: [];
        }
        if(!empty($res['measure_image'])){
            $res['measure_image'] = json_decode($res['measure_image'], true);
        }
        if(!empty($res['plank_house_table_title'])){
            $res['plank_house_table_title'] = json_decode($res['plank_house_table_title'], true);
        }
        if(!empty($res['plank_house_table_data'])){
            $res['plank_house_table_data'] = json_decode($res['plank_house_table_data'], true);
        }
        if(!empty($res['products_base_cdoe'])){
            $res['products_base_cdoe'] = json_decode($res['products_base_cdoe'], true);
        }
        if(!empty($res['specifications_base_cdoe'])){
            $res['specifications_base_cdoe'] = json_decode($res['specifications_base_cdoe'], true);
        }
        //获取更新日志
        $logRes = (new SsyNewProductsLogTable())->where('type_no', $typeNo)->where('type', 5)->orderBy('createtime', 'desc')->paginate(20)->toArray();
        return [
            'data' => $res,
            'log' => $logRes['data']
        ];
    }

    //尺寸表 保存
    public function detailRuleSave($id, $param)
    {
        $measureImage = "";
        if(!empty($param['measure_image'])){
            $measureImage = json_encode(array_column($param['measure_image'], 'url'), JSON_UNESCAPED_UNICODE);
        }
        $wearImage = "";
        if(!empty($param['wear_image'])){
            $wearImage = json_encode(array_column($param['wear_image'], 'url'), JSON_UNESCAPED_UNICODE);
        }
        $plankHouseTableTitle = '';
        if(!empty($param['plank_house_table_title'])){
            $plankHouseTableTitle = json_encode($param['plank_house_table_title'], JSON_UNESCAPED_UNICODE);
        }
        $plankHouseTableData = '';
        if(!empty($param['plank_house_table_data'])){
            $plankHouseTableData = json_encode($param['plank_house_table_data'], JSON_UNESCAPED_UNICODE);
        }
        $productsBaseCdoe = '';
        if(!empty($param['products_base_cdoe'])){
            $productsBaseCdoe = json_encode($param['products_base_cdoe'], JSON_UNESCAPED_UNICODE);
        }
        $specificationsBaseCdoe = '';
        if(!empty($param['specifications_base_cdoe'])){
            foreach ($param['specifications_base_cdoe']['base_size_code'] as $item){
                if(!empty($item['specifications_base_cdoe'])){
                    $specificationsBaseCdoe = json_encode($param['specifications_base_cdoe'], JSON_UNESCAPED_UNICODE);
                    break;
                }
            }
        }
        $data = [
            "wear_image" => $wearImage,
            "measure_image" => $measureImage,
            "be_careful" => $param['be_careful'],
            "reminder" => $param['reminder'],
            "risk" => $param['risk'],
            "plank_house_table_title" => $plankHouseTableTitle,
            "products_base_cdoe" => $productsBaseCdoe,
            "plank_house_table_data" => $plankHouseTableData,
            "specifications_base_cdoe" => $specificationsBaseCdoe,
            "modify_comments" => $param['modify_comments'],
        ];
        $res = (new SsyNewProductsSizeTable())->updateData($id, $data);
        if($res['code'] === 0){
            $user = auth()->guard("api")->user();
            LogRepository::setOperateLog($user->name, "变更尺寸表", $param['type_no'], 5, $data);
        }
        return $res;
    }

    //尺寸表信息--解锁、锁定
    public function setLock($param)
    {
        $user = auth()->guard('api')->user();
        if(!in_array($user->name, ["张毅", "单铭", "徐文波", "黄德芬", "金强"])){
            return ['code' => -1, 'msg' => '抱歉, 你没有操作权限'];
        }
        $label = $param['status'] == 1 ? "锁定" : "解锁";
        $type = (Int)$param['type'];
        $status = (Int)$param['status'];
        $data = [];
        switch ($type){
            case 5:
                $title = "尺寸表";
                $data = ['size_code_status' => $status];
                break;
            case 6:
                $title = "工艺单";
                $data = ['process_sheet_status' => $status];
                break;
            case 8:
                $title = "技术文件";
                $data = ['sealed_status' => $status];
                break;
        }
        if(empty($data)){
            return ['code' => -1, 'msg' => '未知类型操作'];
        }
        $res = (new SsyNewProductsSizeTable())->updateData((Int)$param['id'], $data);
        if($res['code'] === 0){
            LogRepository::setOperateLog($user->name, $label.$title, $param['type_no'], $type);
        }
        return $res;
    }

    public function detailGy($typeNo, $isEdit)
    {
        $res = (new SsyNewProductProcessSheetTable())->where('type_no', $typeNo)->first();
        if(empty($res)){
            return ['msg' => '没有相关数据'];
        }
        $res = $res->toArray();
        if(!empty($res['production_sewing_process_requirements'])){//生产缝制工艺要求
            $res['production_sewing_process_requirements'] = json_decode($res['production_sewing_process_requirements'], true);
        }
        //工艺细节图
        $detailDrawing = !empty($res['detail_drawing']) ? json_decode($res['detail_drawing'], true) : [];
        $res['detail_drawing'] = [];
        foreach ($detailDrawing as $url){
            $res['detail_drawing'][] = ['url' => $url];
        }
        //可撕图
        $res['tearable_label_img'] = $res['tearable_label_img'] ?: "";
        //工艺指示书
        $res['process_instruction'] = !empty($res['process_instruction']) ? json_decode($res['process_instruction'], true) : [];
        if($isEdit){
            foreach($res['process_instruction'] as &$item){
                $imgExtension = pathinfo($item['img'], PATHINFO_EXTENSION);
                $item['img_64'] = "data:image/{$imgExtension};base64,".base64_encode(file_get_contents($item['img']));
            }
            unset($item);
        }
        if(!empty($res['mark_position'])){//唛头位置
            $res['mark_position'] = json_decode($res['mark_position'], true);
        }
        //锁钉要求
        $res['requirements_for_locking_nails'] = !empty($res['requirements_for_locking_nails']) ? json_decode($res['requirements_for_locking_nails'], true) : [];
        if(!empty($res['special_process_requirements'])){//特殊工艺要求
            $res['special_process_requirements'] = json_decode($res['special_process_requirements'], true);
        }
        if(!empty($res['packaging_specification_requirements'])){//包装规格要求
            $res['packaging_specification_requirements'] = json_decode($res['packaging_specification_requirements'], true);
        }
        $res['is_shuixi'] = $res['is_shuixi'] == null ? 0 : $res['is_shuixi'];
        $res['is_gif'] = $res['is_gif'] == null ? 0 : $res['is_gif'];
        $res['is_perform'] = $res['is_perform'] == null ? 0 : $res['is_perform'];
        $res['type_name'] = (new StyleTable())->where('number', $typeNo)->first()->name;
        return $res;
    }

    public function detailGySave($data)
    {
        //生产缝制工艺要求
        $production_sewing_process_requirements = "";
        if($data['production_sewing_process_requirements'] ?? ""){
            $production_sewing_process_requirements = json_encode($data['production_sewing_process_requirements']);
        }
        //工艺细节图
        $detail_drawing = "";
        if($data['detail_drawing'] ?? ""){
            $detail_drawing = json_encode(array_column($data['detail_drawing'], 'url'));
        }
        //工艺指示书
        $process_instruction = "";
        if($data['process_instruction'] ?? ""){
            $process_instruction = json_encode($data['process_instruction']);
        }
        //唛头位置
        $mark_position = "";
        if($data['mark_position'] ?? ""){
            $mark_position = json_encode($data['mark_position']);
        }
        //锁定要求
        $requirements_for_locking_nails = "";
        if($data['requirements_for_locking_nails'] ?? ""){
            $requirements_for_locking_nails = json_encode($data['requirements_for_locking_nails']);
        }
        //特殊工艺要求
        $special_process_requirements = "";
        if($data['special_process_requirements'] ?? ""){
            $special_process_requirements = json_encode($data['special_process_requirements']);
        }
        //包装规格要求
        $packaging_specification_requirements = "";
        if($data['packaging_specification_requirements'] ?? ""){
            $packaging_specification_requirements = json_encode($data['packaging_specification_requirements']);
        }
        //裁剪要求
        $cutting_requirements = $data['cutting_requirements'] ?? "";
        //后道工序
        $subsequent_process = $data['subsequent_process'] ?? "";
        //验收标准
        $acceptance_criteria = $data['acceptance_criteria'] ?? "";
        //可撕标示图
        $tearable_label_img = "";
        if($data['tearable_label_img'] ?? ""){
            $tearable_label_img = $data['tearable_label_img'];
        }
        $saveData = [
            "type_no" => $data['type_no'],
            "production_sewing_process_requirements"=>$production_sewing_process_requirements,
            "detail_drawing"=>$detail_drawing,
            "process_instruction"=>$process_instruction,
            "mark_position"=>$mark_position,
            "requirements_for_locking_nails"=>$requirements_for_locking_nails,
            "special_process_requirements"=>$special_process_requirements,
            "packaging_specification_requirements"=>$packaging_specification_requirements,
            "cutting_requirements"=>$cutting_requirements,
            "subsequent_process"=>$subsequent_process,
            "acceptance_criteria"=>$acceptance_criteria,
            "is_gif" => $data['is_gif'],
            "is_perform" => $data['is_perform'],
            "is_shuixi" => $data['is_shuixi'],
            "tearable_label_img" => $tearable_label_img,
            "executive_standard" => $data['executive_standard'] ?? "",
            "safety_category" => $data['safety_category'] ?? "",
            "add_user" => $data['add_user'],
            "createtime" => date("Y-m-d H:i:s")
        ];
        $user = auth()->guard("api")->user();
        $sheetObj = (new SsyNewProductProcessSheetTable())->where('type_no', $data['type_no'])->first();
        if(!empty($sheetObj)){
            unset($saveData['createtime']);
            LogRepository::setOperateLog($user->name, "变更工艺单", $data['type_no'], 6, $saveData);
            return (new SsyNewProductProcessSheetTable())->updateData($sheetObj->id, $saveData);
        }else{
            LogRepository::setOperateLog($user->name, "创建工艺单", $data['type_no'], 6, $saveData);
            return (new SsyNewProductProcessSheetTable())->createData($saveData);
        }
    }

    public function createDetailFile($param)
    {
        $user = auth()->guard("api")->user();
        $data = [
            'title' => $param['title'],
            'group_id' => $param['group_id'],
            'type_id' => in_array($param['type_id'], [1, 2, 3, 5]) ? $param['type_id'] : null,
            'url' => $param['url'],
            'type_no' => $param['type_no'],
            'status' => 0,
            'username' => $user->name,
            'createtime' => date('Y-m-d H:i:s')
        ];
        $res = (new SsyNewProductsSealedSampleTable())->createData($data);
        if($res['code'] === 0){
            LogRepository::setOperateLog($user->name, "新增技术文件", $param['type_no'], 8);
        }
        return $res;
    }

    public function detailFileList($param)
    {
        return (new SsyNewProductsSealedSampleTable())->where('type_no', $param['type_no'])->orderBy("createtime", "desc")->get()->toArray();
    }

    public function detailFileSave($param)
    {
        $id = (Int)$param['id'];
        $data = [];
        if(isset($param['status']) && $param['status'] != ""){
            $data['status'] = (Int)$param['status'];
        }
        if(isset($param['remarks'])){
            $data['remarks'] = $param['remarks'];
        }
        if(isset($param['type_id'])){
            $data['type_id'] = $param['type_id'];
        }
        if(isset($param['color_title'])){
            $data['color_title'] = $param['color_title'];
        }
        if(empty($data)){
            return ["code" => -1, "msg" => "保存内容不能为空"];
        }
        //更新之前需要把同款下的其他相同文件类别和颜色的文件 禁用
        if(!isset($data['status']) || (isset($data['status']) && $data['status']==1)){
            (new SsyNewProductsSealedSampleTable())->updateDataWhere([
                'id' => ['<>' => $id],
                'type_no' => $param['type_no'],
                'group_id' => $param['group_id'],
                'type_id' => $param['type_id'],
                'color_title' => $param['color_title']
            ], ['status' => 0]);
        }
        return (new SsyNewProductsSealedSampleTable())->updateData($id, $data);
    }

    public function detailMaterialSave($param)
    {
        $id = (Int)$param['id'];
        $data = [
            'sr' => $param['sr']
        ];
        return (new StyleBomSizeConfigTable())->updateData($id, $data);
    }

    public function stop($id, $status)
    {
        return (new StyleTable())->updateData($id, ['approval_state' => $status]);
    }

    public function check($id, $state)
    {
        try{
            $styleObj = (new StyleTable())->where('id', $id)->first()->toArray();
            //线上环境 流程从设计确认到技术确认 群消息通知
            $isProduct = env("APP_ENV") == "PRO";
            if($styleObj['brand_id'] == 1 && $styleObj['state'] == 1 && $state == 2 && $isProduct){
                $chatID = "oc_c247b07ff8196d9a5c13a1334d91cf70";//成人--产品设计-技术对接群
                if(in_array($styleObj['product_category'], ['童配', '童装'])){
                    $chatID = "oc_d9e886afa94110ec1038023df671f189";//童装--童装上新表&详情页面确认群
                }
                //套装编码
                $t17Obj = (new T17Table())->where('id', $styleObj['t17_id'])->first();
                //款式图片
                $imgObj = (new SsyStyleImagesTable())->where('type_no', $styleObj['number'])->first()->toArray();
                $upRes = (new FeishuRepository())->uploadImgMsg([
                    'image_type' => "message",
                    'image' => $imgObj['images']
                ]);
                $postData = [
                    'receive_id' => $chatID,
                    'msg_type' => 'interactive',
                    'content' => json_encode([
                        'type' => 'template',
                        'data' => [
                            'template_id' => 'AAqhKYbCYpY8g',//款式--技术确认通知
                            'template_variable' => [
                                'type_no_img' => ["img_key" => $upRes['data']['image_key'] ?? ""],
                                'type_no' => $styleObj['number'],
                                'year_month' => $styleObj['year']."-".$styleObj['month'],
                                'name' => $styleObj['name'],
                                'short_name' => $styleObj['short_name'],
                                'season' => $styleObj['season'],
                                'target' => $styleObj['target'],
                                'product_category' => $styleObj['product_category'],
                                'brand' => $styleObj['brand'],
                                'detail_category' => $styleObj['detail_category'],
                                'package_number' => $t17Obj->number ?? "",
                                'f3' => $styleObj['f3'],
                                'designer' => $styleObj['designer'],
                                'paper_designer' => $styleObj['paper_designer'],
                                'embroider_designer' => $styleObj['embroider_designer'],
                                'creator' => $styleObj['creator'],
                                'creation_time' => date("Y-m-d",$styleObj['creation_time']+1512460800),
                            ]
                        ]
                    ], JSON_UNESCAPED_UNICODE),
                ];
                (new FeishuRepository())->sendMsg($postData, 'chat_id');
            }
            return (new StyleTable())->updateData($id, ['state' => $state]);
        }catch (\Exception $e){
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public function imageSave($typeNo, $images)
    {
        $imagesList = [];
        foreach ($images as $item){
            $imagesList[] = $item['response']['data'] ?? $item['url'];
        }
        if(empty($imagesList)){
            return ['code' => -1, 'msg' => '未检测到上传的图片信息'];
        }
        $data = [
            'type_no' => $typeNo,
            'createtime' => date('Y-m-d H:i:s'),
            'images' => $images[0]['response']['data'] ?? $images[0]['url'],
            'thumb_images' => $images[0]['response']['data'] ?? $images[0]['url'],
            'images_list' => json_encode($imagesList),
            'thumb_images_list' => json_encode($imagesList)
        ];
        $exist = (new SsyStyleImagesTable())->where('type_no', $typeNo)->first();
        if(empty($exist)){
            $res = (new SsyStyleImagesTable())->createData($data);
        }else{
            $res = (new SsyStyleImagesTable())->updateData($exist->id, $data);
        }
        $res['images'] = $data['images'];
        $res['images_list'] = json_decode($data['images_list'], true);
        return $res;
    }

    public function attachList($typeNo)
    {
        $list = (new SsyStyleAttachTable())->where('type_no', $typeNo)->get()->toArray();
        foreach ($list as &$item){
            $item['type'] = pathinfo($item['url'], PATHINFO_EXTENSION);
        }
        unset($item);
        return $list;
    }

    public function attachDel($id)
    {
        $exist = (new SsyStyleAttachTable())->where('id', $id)->first();
        if(empty($exist)){
            return ['code' => -1, 'msg' => '操作失败：数据不存在'];
        }
        $res = CommonRepository::delectCDN($exist->url, 'file');
        if($res['code'] !== 0){
            return ['code' => -1, 'msg' => $res['msg']];
        }
        return (new SsyStyleAttachTable())->deleteData($id);
    }

    public function dbCheck($typeNo)
    {
        if(!preg_match("/^[A-Z]{3}[0-9]{6}$/", $typeNo)){
            return ['code' => -1, 'msg' => '校验失败：命名组合限制为：3位大写字母 + 6位数字'];
        }
        $exist = (new StyleTable())->where('number', $typeNo)->exists();
        if($exist){
            return ['code' => -1, 'msg' => '校验失败：编码已存在'];
        }
        return ['code' => 0];
    }

    public function del($typeNo)
    {
        $styleObj = (new StyleTable())->where('number', $typeNo)->first();
        if(empty($styleObj)){
            return ['code' => -1, 'msg' => '未发现该款号'];
        }
        $exist = (new ExportOrderProductTable())->where('product_number', $typeNo)->exists();
        if($exist){
            return ['code' => -1, 'msg' => '删除失败：该款号已被[运营订单]依赖'];
        }
        $exist = (new VerifyPriceTable())->where('style_number', $typeNo)->exists();
        if($exist){
            return ['code' => -1, 'msg' => '删除失败：该款号已被[核价单]依赖'];
        }
        try {
            DB::connection("mysql_sj")->beginTransaction();
            (new StyleTable())->deleteData($styleObj->id);
            (new StyleBomTable())->deleteDataWhere(['style_id' => $styleObj->id]);
            (new StyleBomColourConfigTable())->deleteDataWhere(['style_id' => $styleObj->id]);
            (new StyleBomSizeConfigTable())->deleteDataWhere(['style_id' => $styleObj->id]);
            (new StyleColourTable())->deleteDataWhere(['style_id' => $styleObj->id]);
            (new StylePrintingTable())->deleteDataWhere(['style_id' => $styleObj->id]);
            (new StyleSampleProcessesTable())->deleteDataWhere(['style_id' => $styleObj->id]);
            (new StyleT4Table())->deleteDataWhere(['style_id' => $styleObj->id]);
            (new StyleT50Table())->deleteDataWhere(['style_id' => $styleObj->id]);
            (new StyleT68Table())->deleteDataWhere(['style_id' => $styleObj->id]);
            (new StyleTagTable())->deleteDataWhere(['style_id' => $styleObj->id]);
            //写入操作日志
            $user = auth()->guard("api")->user();
            LogRepository::setOperateLog($user->name, "单据删除", $typeNo, 4);
            DB::connection("mysql_sj")->commit();
            return ['code' => 0];
        }catch (\Exception $e){
            DB::connection("mysql_sj")->rollBack();
            return ['code' => -1, 'msg' => "提交失败：".$e->getMessage()];
        }
    }

    public function save($param)
    {
        $user = auth()->guard("api")->user();
        list($styleObj, $materielData, $styleColour, $bomData , $yyData, $images) = [json_decode($param['data'], true),
            json_decode($param['materiel_data'], true), json_decode($param['style_colour'], true), json_decode($param['bom_data'], true),
            json_decode($param['yy_data'], true), json_decode($param['images'], true)];
        $isNew = false;
        if(!($styleObj['id'] ?? "")){
            $isNew = true;
            $res = $this->dbCheck($styleObj['number']);
            if($res['code'] !== 0){
                return $res;
            }
        }
        //dd($styleObj, $materielData, $bomData, $bomXhData ,$styleColour, $yyData, $images);
        try {
            DB::connection("mysql_sj")->beginTransaction();
            //保存主表
            $styleRes = $this->saveStyle($styleObj, $user);
            if($styleRes['code'] !== 0){
                DB::connection("mysql_sj")->rollBack();
                return $styleRes;
            }
            //样衣工时
            $sampleRes = $this->saveSample($yyData, $styleRes['style_id']);
            if($sampleRes['code'] !== 0){
                DB::connection("mysql_sj")->rollBack();
                return $sampleRes;
            }
            //款式颜色
            $colourRes = $this->saveColour($styleColour, $styleRes['style_id'], $isNew);
            if($colourRes['code'] !== 0){
                DB::connection("mysql_sj")->rollBack();
                return $colourRes;
            }
            //物料清单、大货BOM、用料详情（单耗）、物料颜色
            $bomRes = $this->saveBom($materielData, $styleRes['style_id'], $colourRes['colour_id'], $isNew, 0);
            if($bomRes['code'] !== 0){
                DB::connection("mysql_sj")->rollBack();
                return $bomRes;
            }
            $bomRes = $this->saveBom($bomData, $styleRes['style_id'], $colourRes['colour_id'], $isNew, 1);
            if($bomRes['code'] !== 0){
                DB::connection("mysql_sj")->rollBack();
                return $bomRes;
            }
            DB::connection("mysql_sj")->commit();
            //款式图片
            If(!empty($images)){
                $imageData = [
                    'type_no' => $styleObj['number'],
                    'createtime' => date('Y-m-d H:i:s'),
                    'images' => $images[0],
                    'thumb_images' => $images[0],
                    'images_list' => json_encode($images),
                    'thumb_images_list' => json_encode($images)
                ];
                $exist = (new SsyStyleImagesTable())->where('type_no', $imageData['type_no'])->first();
                if(empty($exist)){
                    (new SsyStyleImagesTable())->createData($imageData);
                }else{
                    (new SsyStyleImagesTable())->updateData($exist->id, $imageData);
                }
            }
            return ['code' => 0];
        }catch (\Exception $e){
            DB::connection("mysql_sj")->rollBack();
            return ['code' => -1, 'msg' => "提交失败：".$e->getMessage()];
        }
        return ['code' => 0];
    }

    public function saveStyle($styleObj, $user)
    {
        $data = [
            'number' => $styleObj['number'],
            't17_id' => (Int)$styleObj['t17_id'],
            'name' => $styleObj['name'],
            'short_name' => $styleObj['short_name'],
            'type_id' => (Int)$styleObj['type_id'],
            'product_category_id' => (Int)$styleObj['product_category_id'],
            'product_category' => $styleObj['product_category'],
            'detail_category_id' => (Int)$styleObj['detail_category_id'],
            'detail_category' => $styleObj['detail_category'],
            'designer_id' => (Int)$styleObj['designer_id'],
            'designer' => $styleObj['designer'],
            'f3_id' => (Int)$styleObj['f3_id'],
            'f3' => $styleObj['f3'],
            'paper_designer_id' => (Int)($styleObj['paper_designer_id'] ?? 0),
            'paper_designer' => $styleObj['paper_designer'] ?? "",
            'year' => (Int)$styleObj['year'],
            'month' => (Int)$styleObj['month'],
            'season_id' => (Int)$styleObj['season_id'],
            'season' => $styleObj['season'],
            'brand_id' => (Int)$styleObj['brand_id'],
            'brand' => $styleObj['brand'],
            'target_id' => (Int)$styleObj['target_id'],
            'target' => $styleObj['target'],
            't1_id' => (Int)$styleObj['t1_id'],
            't1' => $styleObj['t1'],
            'composition' => $styleObj['composition'] ?? "",
            'f79' => $styleObj['f79'] ?? "",
            't5' => $styleObj['t5'] ?? "",
            't6' => $styleObj['t6'] ?? "",
            'f7' => $styleObj['f7'] ?? "",
            'f8_id' => (Int)($styleObj['f8_id'] ?? 0),
            'f8_short' => $styleObj['f8_short'] ?? "",
            'f9_id' => (Int)($styleObj['f9_id'] ?? 0),
            'f9_short' => $styleObj['f9_short'] ?? "",
            'f10_id' => (Int)($styleObj['f10_id'] ?? 0),
            'f10_short' => $styleObj['f10_short'] ?? "",
            'f11_id' => (Int)($styleObj['f11_id'] ?? 0),
            'f11_short' => $styleObj['f11_short'] ?? "",
            'f12_id' => (Int)($styleObj['f12_id'] ?? 0),
            'f12_short' => $styleObj['f12_short'] ?? "",
            'f12' => $styleObj['f12'] ?? "",
            'p12_id' => (Int)($styleObj['p12_id'] ?? 0),
            'p12_short' => $styleObj['p12_short'] ?? "",
            'f13' => (Int)($styleObj['f13'] ?? 0),
            'f14' => (Int)($styleObj['f14'] ?? 0),
            'f15' => (Int)($styleObj['f15'] ?? 0),
            'f19' => (Int)($styleObj['f19'] ?? 0),
            'f20' => (Int)($styleObj['f20'] ?? 0),
            'f21' => (Int)($styleObj['f21'] ?? 0),
            'comment' => $styleObj['comment'] ?? "",
            'f36' => $styleObj['f36'] ?? "",
            'approval_state' => (Int)($styleObj['approval_state'] ?? 0),
            'state' => (Int)($styleObj['state'] ?? 0),
            'creator_id' => $user->id,
            'creator' => $user->name,
            'creation_time' => strtotime(date('Y-m-d')) - 1512460800,
            'style_size_id' => (Int)($styleObj['style_size_id'] ?? 0),
            'embroider_designer_id' => (Int)($styleObj['embroider_designer_id'] ?? 0),
            'embroider_designer' => $styleObj['embroider_designer'] ?? ""
        ];
        if($styleObj['id'] ?? ""){
            unset($data['creation_time']);
            $res = (new StyleTable())->updateData((Int)$styleObj['id'], $data);
            if($res['code'] !== 0){
                return $res;
            }
        }else{
            $res = (new StyleTable())->createData($data);
            if($res['code'] !== 0){
                return $res;
            }
            $styleObj['id'] = $res['id'];
        }
        //工艺类型
        $t68Data = [
            'style_id' => $styleObj['id'],
            't68_id' => $styleObj['t68_id'] ?? 0,
            't68' => $styleObj['t68'] ?? ""
        ];
        if($styleObj['style_t68_id'] ?? ""){
            (new StyleT68Table())->updateData($styleObj['style_t68_id'], $t68Data);
        }else{
            (new StyleT68Table())->createData($t68Data);
        }
        //纹样描述
        if($styleObj['style_tag'] ?? []){
            $styleTagIds = [];
            foreach ($styleObj['style_tag'] as $item){
                $tagData = ['style_id' => $styleObj['id'], 'value' => $item['value']];
                if($item['id'] ?? ""){
                    (new StyleTagTable())->updateData($item['id'], $tagData);
                    $styleTagIds[] = $item['id'];
                }else{
                    $res = (new StyleTagTable())->createData($tagData);
                    $styleTagIds[] = $res['id'] ?? "";
                }
            }
            (new StyleTagTable())->deleteDataWhere(['style_id' => $styleObj['id'], 'id' => ['not_in' => $styleTagIds]]);
        }else{
            (new StyleTagTable())->deleteDataWhere(['style_id' => $styleObj['id']]);
        }
        //商品属性
        if($styleObj['style_t4'] ?? []){
            $styleT4Ids = [];
            foreach ($styleObj['style_t4'] as $item) {
                $t4Data = ['style_id' => $styleObj['id'], 't4_id' => $item['id'], 't4' => $item['name']];
                if($item['_id'] ?? ""){
                    (new StyleT4Table())->updateData($item['_id'], $t4Data);
                    $styleT4Ids[] = $item['_id'];
                }else{
                    $res = (new StyleT4Table())->createData($t4Data);
                    $styleT4Ids[] = $res['id'];
                }
            }
            (new StyleT4Table())->deleteDataWhere(['style_id' => $styleObj['id'], 'id' => ['not_in' => $styleT4Ids]]);
        }else{
            (new StyleT4Table())->deleteDataWhere(['style_id' => $styleObj['id']]);
        }
        return ['code' => 0, 'style_id' => $styleObj['id']];
    }

    public function saveSample($yyData, $styleId)
    {
        $ids = array_column($yyData, 'id');
        (new StyleSampleProcessesTable())->deleteDataWhere(['id' => ['not_in' => $ids], 'style_id' => $styleId]);
        foreach ($yyData as $position => $item){
            $data = [
                'style_id' => (Int)$styleId,
                'sample_processes_id' => (Int)$item['sample_processes_id'],
                'sample_processes' => $item['sample_processes'],
                'time' => (Double)$item['time'],
                'position' => $position+1
            ];
            if($item['id'] ?? ""){
                $res = (new StyleSampleProcessesTable())->updateData($item['id'], $data);
            }else{
                $res = (new StyleSampleProcessesTable())->createData($data);
            }
            if($res['code'] !== 0){
                return $res;
            }
        }
        return ['code' => 0];
    }

    public function saveBomXH($bomXhData, $styleId)
    {
        $ids = array_column($bomXhData, 'id');
        $delRes = (new StyleT50Table())->deleteDataWhere(['id' => ['not_in' => $ids], 'style_id' => $styleId]);
        $isUp = $delRes['code'] === 0 && $delRes['data'] > 0 ? true : false;
        $upData = [];
        foreach ($bomXhData as $position => $item){
            $data = [
                'style_id' => $styleId,
                'position' => $position+1,
                'f51' => $item['f51'],
                'part' => $item['part'],
                'f52' => (Int)$item['f52'],
                'f53' => $item['f53'],
                'f54' => (Double)$item['f54'],
                'f55' => (Double)$item['f55'],
                'comment' => $item['comment'],
            ];
            $res = ['code' => 0];
            if($item['id'] ?? ""){
                $existObj = (new StyleT50Table())->where('id', $item['id'])->first()->toArray();
                list($existObj['f52'], $existObj['f54'], $existObj['f55']) = [(Int)$existObj['f52'], (Double)$existObj['f54'], (Double)$existObj['f55']];
                if(array_diff_assoc($data, $existObj)){
                    $isUp = true;
                    $res = (new StyleT50Table())->updateData($item['id'], $data);
                }
            }else{
                $isUp = true;
                $res = (new StyleT50Table())->createData($data);
            }
            if($res['code'] !== 0){
                return $res;
            }
            $upData[] = $data;
        }
        if($isUp){
            $user = auth()->guard("api")->user();
            LogRepository::setOperateLog($user->name, "变更绣花BOM", $styleId, 11, $upData);
        }
        return ['code' => 0];
    }

    public function saveColour($styleColour, $styleId, $isNew)
    {
        $colourId = [];
        foreach ($styleColour as $position => $item){
            $data = [
                'style_id' => $styleId,
                'position' => $position+1,
                'colour_id' => (Int)$item['colour_id'],
                'colour_number' => $item['colour_number'],
                'colour' => $item['colour'],
                'colour_value' => $item['colour_value'],
                'is_product' => 1
            ];
            if($isNew || preg_match("/^#_/is", $item['id'])){
                $res = (new StyleColourTable())->createData($data);
                if($res['code'] !== 0){
                    return $res;
                }
                $colourId[$item['id']] = $res['id'];
            }else{
                $colourId[$item['id']] = $item['id'];
            }
        }
        $ids = array_values($colourId);
        if(!empty($ids)){
            (new StyleColourTable())->deleteDataWhere(['id' => ['not_in' => $ids], 'style_id' => $styleId]);
        }
        return ['code' => 0, 'colour_id' => $colourId];
    }

    public function saveBom($materielData, $styleId, $colourId, $isNew, $isProduct)
    {
        //dd($materielData, $styleId, $colourId, $isNew, $isProduct);
        //清除多余的物料
        $materielIds = array_column($materielData, 'id');
        $delRes = (new StyleBomTable())->deleteDataWhere(['id' => ['not_in' => $materielIds], 'style_id' => $styleId, 'is_product' => $isProduct]);
        $isUp = $delRes['code'] === 0 && $delRes['data'] > 0 ? true : false;
        $upData = [];
        $bomSizeConfigIds = [];
        $bomColourIds = [];
        $position = 1;
        foreach ($materielData as $item){
            $data = [
                'style_id' => $styleId,
                'position' => $position,
                'type' => 3,
                'materiel_id' => $item['materiel_id'],
                'materiel_number' => $item['materiel_number'],
                'materiel' => $item['materiel'],
                'materiel_major_category_id' => $item['materiel_major_category_id'],
                'materiel_major_category' => $item['materiel_major_category'],
                'materiel_minor_category_id' => $item['materiel_minor_category_id'],
                'materiel_minor_category' => $item['materiel_minor_category'],
                'materiel_major_unit_id' => $item['materiel_major_unit_id'],
                'materiel_major_unit' => $item['materiel_major_unit'],
                'materiel_attribute_id' => $item['materiel_attribute_id'],
                'materiel_attribute' => $item['materiel_attribute'],
                'part' => $item['part'],
                'is_multiple_colour' => (Int)($item['is_multiple_colour'] ?? 0),
                'confirm' => (Int)($item['confirm'] ?? 1),
                'comment' => $item['comment'] ?? "",
                'f35' => $item['f35'] ?? "",
                'supplier_id' => $item['supplier_id'],
                'supplier' => $item['supplier'],
                'supplier_contact_name' => $item['supplier_contact_name'],
                'supplier_phone' => $item['supplier_phone'],
                'supplier_address' => $item['supplier_address'],
                'price' => (Double)($item['price'] ?? 0),
                'is_product' => (Int)$item['is_product']
            ];
            $position++;
            if($isNew || !isset($item['id'])){
                $res = (new StyleBomTable())->createData($data);
                if($res['code'] !== 0){
                    return $res;
                }
                $data['style_bom_id'] = $res['id'];
                $isUp = true;
            }else{
                $existObj = (new StyleBomTable())->where('id', $item['id'])->first()->toArray();
                $existObj['price'] = (Double)$existObj['price'];
                if(array_diff_assoc($data, $existObj)){
                    $isUp = true;
                    $res = (new StyleBomTable())->updateData($item['id'], $data);
                    if($res['code'] !== 0){
                        return $res;
                    }
                }
                $data['style_bom_id'] = $item['id'];
            }
            $upData[] = $item;
            //用料详情（单耗）
            $sr = ($item['style_bom_size_config']['material_sr_e']??"") || ($item['style_bom_size_config']['material_sr_w']??"") ?
                $item['style_bom_size_config']['material_sr_e'].":".$item['style_bom_size_config']['material_sr_w'] : "";
            $bomSizeConfig = [
                'style_id' => $styleId,
                'style_bom_id' => $data['style_bom_id'],
                'amount' => (Double)($item['style_bom_size_config']['amount'] ?? 0),
                'content' => json_encode($item['style_bom_size_config']['content'] ?? [], JSON_UNESCAPED_UNICODE),
                'sr' => $sr,
                'is_product' => (Int)$item['is_product']
            ];
            if($isNew || !isset($item['style_bom_size_config']['id'])){
                $isUp = true;
                $res = (new StyleBomSizeConfigTable())->createData($bomSizeConfig);
                if($res['code'] !== 0){
                    return $res;
                }
                $bomSizeConfigIds[] = $res['id'];
            }else{
                $existObj = (new StyleBomSizeConfigTable())->where('id', $item['style_bom_size_config']['id'])->first()->toArray();
                $existObj['amount'] = (Double)$existObj['amount'];
                if(array_diff_assoc($bomSizeConfig, $existObj)){
                    $isUp = true;
                    $res = (new StyleBomSizeConfigTable())->updateData($item['style_bom_size_config']['id'], $bomSizeConfig);
                    if($res['code'] !== 0){
                        return $res;
                    }
                }
                $bomSizeConfigIds[] = $item['style_bom_size_config']['id'];
            }
            //物料颜色
            foreach ($colourId as $sourceColourId => $styleColourId){
                if(!isset($item['style_bom_colour_config'][$sourceColourId])){
                    continue;
                }
                $colourContent = $item['style_bom_colour_config'][$sourceColourId][0] ?? [];
                $colourData = [
                    'style_id' => $styleId,
                    'style_bom_id' => $data['style_bom_id'],
                    'style_colour_id' => $styleColourId,
                    'is_product' => $data['is_product'],
                    'content' => json_encode(empty($colourContent) || !isset($colourContent['code']) ? [] : [
                        ["code" => $colourContent['code'], "name" => "颜色", "value" => $colourContent['value'], "change" => false]
                    ], JSON_UNESCAPED_UNICODE)
                ];
                if(isset($colourContent['style_bom_colour_id']) && !in_array($colourContent['style_bom_colour_id'], $bomColourIds)){
                    $existObj = (new StyleBomColourConfigTable())->where('id', $colourContent['style_bom_colour_id'])->first()->toArray();
                    $existObj['content'] = preg_replace("/\s/is", "", $existObj['content']);
                    if(array_diff_assoc($colourData, $existObj)){
                        $isUp = true;
                        (new StyleBomColourConfigTable())->updateData($colourContent['style_bom_colour_id'], $colourData);
                    }
                    $bomColourIds[] = $colourContent['style_bom_colour_id'];
                }else{
                    $isUp = true;
                    $res = (new StyleBomColourConfigTable())->createData($colourData);
                    $bomColourIds[] = $res['id'];
                }
            }
        }
        if($isUp){
            $user = auth()->guard("api")->user();
            $remark = $isProduct == 1 ? "大货BOM" : "物料清单";
            $type = $isProduct == 1 ? 10 : 9;
            LogRepository::setOperateLog($user->name, "变更{$remark}", $styleId, $type, $upData);
        }
        (new StyleBomSizeConfigTable())->deleteDataWhere(['style_id' => $styleId, 'id' => ['not_in' => $bomSizeConfigIds], 'is_product' => $isProduct]);
        (new StyleBomColourConfigTable())->deleteDataWhere(['style_id' => $styleId, 'id' => ['not_in' => $bomColourIds], 'is_product' => $isProduct]);
        return ['code' => 0];
    }
}
